package com.snb.play.dwebtoon;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.WindowManager;

import com.snb.play.dwebtoon.data.DTO_WebToon;
import com.snb.play.dwebtoon.util.BinderManager;
import com.snb.play.dwebtoon.util.DBProvider;
import com.snb.play.dwebtoon.util.Logger;
import com.snb.play.dwebtoon.util.RESTFulClient;
import com.snb.play.dwebtoon.util.RecycleUtils;

public abstract class BaseActivity extends Activity {

	protected static BinderManager gBinderManager;
	protected ProgressDialog gProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if (gBinderManager == null) {
			gBinderManager = new BinderManager();
		}
		gBinderManager.doBindService(this);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}
	private BinderManager getBinder() {
		if (gBinderManager == null) {
			gBinderManager = new BinderManager();
		}
		return gBinderManager;
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		if (gBinderManager != null && gBinderManager.getService() != null)

		registerReceiver(mDownLoadRcv, new IntentFilter("snb.comic.downComplete"));
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		unregisterReceiver(mDownLoadRcv);
	}

	protected DownLoadRcv mDownLoadRcv = new DownLoadRcv();

	protected class DownLoadRcv extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			refresh(intent.getStringExtra("TITLE"));
		}
	}

	protected abstract void refresh(String aString);

	protected BinderManager getService() {

		return gBinderManager;
	}

	protected synchronized RESTFulClient getRest() {
		return getBinder().getService().getRest();
	} 

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		gBinderManager.doUbBindService(this);
		if (this.getClass().getName().indexOf("WebToon") > -1) {
			Logger.d("DIE ", "OK !!");
			DBProvider.getInstance().close();
		}
		RecycleUtils.recursiveRecycle(getWindow().getDecorView());
		System.gc();
		super.onDestroy();
	}

	protected void setLastToonUp(String aMainToonId, boolean aCurrenTime) {
		DTO_WebToon lToon = new DTO_WebToon();
		lToon.id = aMainToonId;
		lToon = (DTO_WebToon) DBProvider.getInstance().getObjByID(lToon);
		if (aCurrenTime || lToon.lastTouch == null || lToon.lastTouch.length() == 0)
			lToon.lastTouch = String.valueOf(System.currentTimeMillis());
		else
			lToon.lastTouch = String.valueOf(Long.valueOf(lToon.lastTouch) + 500);

		DBProvider.getInstance().updateObjById(lToon);
	}
}
